<?php

namespace Common\Model;

use Think\Model;

/**
 * 用户私有文档关联模型
 * Class UserPDocModel
 * @package Common\Model
 */
class UserPDocModel extends Model
{

    const ALL = 0;          // 文档状态[正、隐、冻]
    const NORMAL_HIDE = 1;       // 文档状态[正、隐]
    const NORMAL = 2;       // 文档状态[正]

    const USER_PDOC_KEY = 'userpdoc:';    // 用户私有文档缓存键名

    /**
     * 获取用户私有文档ID列表数组，如：[1,2,3]
     * @param $uid
     * @param int $type 0=>[正、隐、冻],1=>[正、隐],2=>[正]
     * @return array|null
     */
    public static function getUserPDocsId($uid, $type = self::ALL){
        $key = self::USER_PDOC_KEY.$uid;
        $result = S($key);
        if(false === $result){
            $result = M('Doc')->where(['uid' => $uid, 'bid' => 0])->field('id,status')->select();
            if(false !== $result){
                S($key, is_null($result) ? [] : $result);
            }
        }
        if(!$result){
            return null;
        }
        $arr = array();
        if ($type == self::ALL) {
            foreach($result as $v){
                $arr[] = $v['id'];
            }
        } else if ($type == self::NORMAL_HIDE) {
            foreach($result as $v){
                if ($v['status'] != DocModel::DELTEL) {
                    $arr[] = $v['id'];
                }
            }
        } else if ($type == self::NORMAL) {
            foreach($result as $v){
                if ($v['status'] == DocModel::NORMAL) {
                    $arr[] = $v['id'];
                }
            }
        }
        return $arr;
    }

    /**
     * 分页获取用户收藏的文档信息
     * @param $uid
     * @param int $type 0=>[正、隐、冻],1=>[正、隐],2=>[正]
     * @param bool $all
     * @return array|null
     */
    public static function getUserPDocsInfo($uid, $type = self::ALL, $all = true){
        $dids = self::getUserPDocsId($uid, $type);
        if(!$dids){
            return null;
        }
        $result = [];
        foreach ($dids as $v) {
            $result[] = DocModel::getDocById($v, $all);
        }
        return $result;
    }

    /**
     * 获取用户私有文档的数量
     * @param      $uid
     * @param int $type 0=>[正、隐、冻],1=>[正、隐],
     * @return int
     */
    public static function getUserPDocsCount($uid, $type = self::ALL){
        $dids = self::getUserPDocsId($uid, $type);
        return $dids ? count($dids) : 0;
    }

    public static function clearCache($uid){
        $key = self::USER_PDOC_KEY.$uid;
        S($key, null);
    }

}